const express = require('express');
const router = express.Router();
const dayjs = require("dayjs");
const superagent = require('superagent');
require("superagent-charset")(superagent);

const BoardModel = require('../model/board');
const UnitModel = require('../model/unit');


router.get("/find",async (req,res)=>{
    let rows = await BoardModel.find().select("-__v");

    res.send({
        code: 0,
        data: {
            rows
        }
    })
})


router.get("/detail",async (req,res)=>{
    try {
        let rows = await BoardModel.findOne({_id: req.query.id}).populate({path:'units',select: '-__v'}).select("-__v");

        res.send({
            code: 0,
            data: rows
        })
    } catch (e){
        res.send({
            code: 1,
            msg: e.toString()
        })
    }

})


router.post("/add",async (req,res)=>{

    try {
        let board = await BoardModel.create({
            range: 14,
            name: req.body.name
        })

        res.send({
            code: 0,
            data: board
        })

    } catch(e){
        console.error(e);
        res.send({
            code: 1,
            msg: e.toString()
        })
    }

})


router.post('/removeUnit',async (req,res)=>{

    let id = req.body.id;

    try {
        await UnitModel.deleteOne({ _id: id });

        res.send({
            code: 0
        })

    } catch (e){
        console.error(e)
        res.send({
            code: 1,
            msg: e
        })
    }



})



async function getStockKline(code,range){
    let i = code;
    let a = code.split(".");

    let mk = "SH" == (null == i || null === (a = i.split(".")) || void 0 === a ? void 0 : a[1]) ? "1" : "0";

    console.log(mk+"."+a[0],dayjs().format("YYYYMMDD"))

    let result = await superagent.get("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .set('Content-Type','application/json; charset=UTF-8')
        .query({
            secid: mk+"."+a[0],
            fields1: "f1,f2,f3,f7",
            fields2: "f51,f52,f62,f63",
            lmt: 0,
            pos: dayjs().format("YYYYMMDD"),
            num: 0 - range,
        })

    let data = result.body.data;


    if (data){
        console.log("获取k线成功")
        return data.klines;
    } else {

        console.error("获取k线失败")
        return null;
    }
}

router.get('/sync-today',async (req,res)=>{

    let {code} = req.query;

    let a = code.split(".");

    let mk = "SH" == (null == code || null === (a = code.split(".")) || void 0 === a ? void 0 : a[1]) ? "1" : "0";

    let result = await superagent.get("https://push2.eastmoney.com/api/qt/stock/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .set('Content-Type','application/json; charset=UTF-8')
        .query({
            secid: mk+"."+a[0],
            fields: "f110,f107,f111,f181,f135,f137,f140,f143,f117,f138,f139,f141,f142,f144,f145,f146,f149,f147,f148,f194,f195,f196,f197,f472,f439,f770"
        })

    res.send({
        code: 0,
        data: result.body.data
    })
})

router.get('/sync',async (req,res)=>{

    try {
        let rows = await BoardModel.findOne({_id: req.query.id}).populate({path:'units',select: '-__v'})

        let msg = "";

        for (let i = 0;i<rows.units.length;i++){

            let unit = await UnitModel.findById(rows.units[i]._id.toString()).exec()

            let klines = await getStockKline(unit.code,req.query.range);
            if(klines){
                unit.klines = klines;
                unit.save();
            } else{
                msg += unit.stockCode+"获取失败" + '\n';
            }
        }


        rows = await BoardModel.findOne({_id: req.query.id}).populate({path:'units',select: '-__v'})

        rows.range = Number(req.query.range);

        rows.updatedAt = new Date();

        rows.save();

        res.send({
            code: 0,
            data: rows,
            msg
        })
    } catch (e){
        console.error(e)
        res.send({
            code: 1,
            msg: e.toString()
        })
    }


})


module.exports = router;
